<template>
  <div class="system-tools-test">
    <div class="page-header">
      <h1>🔧 系统工具测试</h1>
      <p>系统缓存、日志、监控、健康检查等工具测试</p>
    </div>

    <div class="tools-grid">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-card title="🗄️ 缓存管理测试" class="tool-card">
            <div class="tool-content">
              <a-form layout="vertical">
                <a-form-item label="缓存类型">
                  <a-select v-model:value="cacheType">
                    <a-select-option value="redis">Redis缓存</a-select-option>
                    <a-select-option value="memory">内存缓存</a-select-option>
                    <a-select-option value="session">会话缓存</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="操作类型">
                  <a-radio-group v-model:value="cacheOperation">
                    <a-radio value="clear">清空缓存</a-radio>
                    <a-radio value="refresh">刷新缓存</a-radio>
                    <a-radio value="stats">缓存统计</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="testCache" :loading="cacheLoading">
                    执行缓存测试
                  </a-button>
                </a-form-item>
              </a-form>
            </div>
          </a-card>
        </a-col>

        <a-col :span="12">
          <a-card title="📝 日志管理测试" class="tool-card">
            <div class="tool-content">
              <a-form layout="vertical">
                <a-form-item label="日志级别">
                  <a-select v-model:value="logLevel">
                    <a-select-option value="DEBUG">DEBUG</a-select-option>
                    <a-select-option value="INFO">INFO</a-select-option>
                    <a-select-option value="WARN">WARN</a-select-option>
                    <a-select-option value="ERROR">ERROR</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="日志模块">
                  <a-select v-model:value="logModule">
                    <a-select-option value="payment">支付模块</a-select-option>
                    <a-select-option value="merchant">商户模块</a-select-option>
                    <a-select-option value="channel">渠道模块</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="testLog" :loading="logLoading">
                    生成测试日志
                  </a-button>
                </a-form-item>
              </a-form>
            </div>
          </a-card>
        </a-col>

        <a-col :span="12">
          <a-card title="💓 健康检查测试" class="tool-card">
            <div class="tool-content">
              <a-form layout="vertical">
                <a-form-item label="检查项目">
                  <a-checkbox-group v-model:value="healthChecks">
                    <a-checkbox value="database">数据库连接</a-checkbox>
                    <a-checkbox value="redis">Redis连接</a-checkbox>
                    <a-checkbox value="payment_channel">支付渠道</a-checkbox>
                    <a-checkbox value="external_api">外部API</a-checkbox>
                  </a-checkbox-group>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="testHealth" :loading="healthLoading">
                    执行健康检查
                  </a-button>
                </a-form-item>
              </a-form>
            </div>
          </a-card>
        </a-col>

        <a-col :span="12">
          <a-card title="📊 性能监控测试" class="tool-card">
            <div class="tool-content">
              <a-form layout="vertical">
                <a-form-item label="监控指标">
                  <a-checkbox-group v-model:value="monitorMetrics">
                    <a-checkbox value="cpu">CPU使用率</a-checkbox>
                    <a-checkbox value="memory">内存使用率</a-checkbox>
                    <a-checkbox value="disk">磁盘使用率</a-checkbox>
                    <a-checkbox value="network">网络流量</a-checkbox>
                  </a-checkbox-group>
                </a-form-item>
                <a-form-item label="监控时长">
                  <a-select v-model:value="monitorDuration">
                    <a-select-option value="1m">1分钟</a-select-option>
                    <a-select-option value="5m">5分钟</a-select-option>
                    <a-select-option value="10m">10分钟</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item>
                  <a-button type="primary" @click="testMonitor" :loading="monitorLoading">
                    开始性能监控
                  </a-button>
                </a-form-item>
              </a-form>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 实时状态展示 -->
    <div class="status-display">
      <h3>🔍 系统状态</h3>
      <a-row :gutter="16">
        <a-col :span="6">
          <a-statistic title="在线用户" :value="systemStatus.onlineUsers" :precision="0" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="内存使用率" :value="systemStatus.memoryUsage" suffix="%" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="CPU使用率" :value="systemStatus.cpuUsage" suffix="%" />
        </a-col>
        <a-col :span="6">
          <a-statistic title="磁盘使用率" :value="systemStatus.diskUsage" suffix="%" />
        </a-col>
      </a-row>
    </div>

    <!-- 测试结果 -->
    <div class="test-results" v-if="testResults.length > 0">
      <h3>📋 测试结果</h3>
      <a-list :data-source="testResults" item-layout="horizontal">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta>
              <template #title>
                <span>{{ item.type }}</span>
                <a-tag :color="item.status === 'success' ? 'green' : 'red'" style="margin-left: 8px;">
                  {{ item.status === 'success' ? '成功' : '失败' }}
                </a-tag>
              </template>
              <template #description>
                <div>{{ item.message }}</div>
                <div class="result-time">{{ item.timestamp }}</div>
              </template>
            </a-list-item-meta>
            <template #actions>
              <a @click="viewDetails(item)">查看详情</a>
            </template>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'

const cacheType = ref('redis')
const cacheOperation = ref('stats')
const logLevel = ref('INFO')
const logModule = ref('payment')
const healthChecks = ref(['database', 'redis'])
const monitorMetrics = ref(['cpu', 'memory'])
const monitorDuration = ref('1m')

const cacheLoading = ref(false)
const logLoading = ref(false)
const healthLoading = ref(false)
const monitorLoading = ref(false)

const testResults = ref<any[]>([])
const systemStatus = reactive({
  onlineUsers: 0,
  memoryUsage: 0,
  cpuUsage: 0,
  diskUsage: 0
})

let statusInterval: number

const testCache = async () => {
  cacheLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))

    const result = {
      id: Date.now(),
      type: '缓存管理测试',
      status: 'success',
      timestamp: new Date().toLocaleString(),
      message: `${cacheType.value} ${cacheOperation.value} 操作完成`,
      details: {
        cacheType: cacheType.value,
        operation: cacheOperation.value,
        duration: `${Math.floor(Math.random() * 500) + 100}ms`
      }
    }

    testResults.value.unshift(result)
    message.success('缓存测试完成')
  } catch (error) {
    message.error('缓存测试失败')
  } finally {
    cacheLoading.value = false
  }
}

const testLog = async () => {
  logLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 800))

    const result = {
      id: Date.now(),
      type: '日志管理测试',
      status: 'success',
      timestamp: new Date().toLocaleString(),
      message: `${logModule.value} 模块 ${logLevel.value} 级别日志生成成功`,
      details: {
        logLevel: logLevel.value,
        logModule: logModule.value,
        logCount: Math.floor(Math.random() * 100) + 10
      }
    }

    testResults.value.unshift(result)
    message.success('日志测试完成')
  } catch (error) {
    message.error('日志测试失败')
  } finally {
    logLoading.value = false
  }
}

const testHealth = async () => {
  healthLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1500))

    const result = {
      id: Date.now(),
      type: '健康检查测试',
      status: 'success',
      timestamp: new Date().toLocaleString(),
      message: `${healthChecks.value.length} 项检查完成，全部正常`,
      details: {
        checkedItems: healthChecks.value,
        passedCount: healthChecks.value.length,
        failedCount: 0
      }
    }

    testResults.value.unshift(result)
    message.success('健康检查完成')
  } catch (error) {
    message.error('健康检查失败')
  } finally {
    healthLoading.value = false
  }
}

const testMonitor = async () => {
  monitorLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 2000))

    const result = {
      id: Date.now(),
      type: '性能监控测试',
      status: 'success',
      timestamp: new Date().toLocaleString(),
      message: `${monitorDuration.value} 监控完成，${monitorMetrics.value.length} 项指标正常`,
      details: {
        monitorMetrics: monitorMetrics.value,
        duration: monitorDuration.value,
        avgCpu: `${Math.floor(Math.random() * 30) + 20}%`,
        avgMemory: `${Math.floor(Math.random() * 40) + 30}%`
      }
    }

    testResults.value.unshift(result)
    message.success('性能监控完成')
  } catch (error) {
    message.error('性能监控失败')
  } finally {
    monitorLoading.value = false
  }
}

const viewDetails = (item: any) => {
  message.info(`查看 ${item.type} 详细信息`)
}

const updateSystemStatus = () => {
  // 模拟系统状态更新
  systemStatus.onlineUsers = Math.floor(Math.random() * 100) + 50
  systemStatus.memoryUsage = Math.floor(Math.random() * 20) + 60
  systemStatus.cpuUsage = Math.floor(Math.random() * 30) + 20
  systemStatus.diskUsage = Math.floor(Math.random() * 15) + 45
}

onMounted(() => {
  updateSystemStatus()
  statusInterval = setInterval(updateSystemStatus, 5000)
})

onUnmounted(() => {
  if (statusInterval) {
    clearInterval(statusInterval)
  }
})
</script>

<style scoped>
.system-tools-test {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.page-header p {
  color: #666;
  margin: 8px 0 0 0;
}

.tools-grid {
  margin-bottom: 24px;
}

.tool-card {
  height: 100%;
  margin-bottom: 16px;
}

.tool-content {
  min-height: 180px;
}

.status-display {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.status-display h3 {
  margin-top: 0;
  color: #333;
  margin-bottom: 16px;
}

.test-results {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.test-results h3 {
  margin-top: 0;
  color: #333;
}

.result-time {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.ant-statistic {
  text-align: center;
}

.ant-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.ant-radio-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>